package com.lxl.bt.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.view.View
import androidx.databinding.DataBindingUtil
import com.lxl.bt.R
import com.lxl.bt.bean.CreateOrderBody
import com.lxl.bt.bean.DianliBean
import com.lxl.bt.bean.ProductBean
import com.lxl.bt.databinding.ActivityPayBinding
import com.lxl.bt.databinding.PopwindowBuyBinding
import com.lxl.bt.databinding.ToolbarTitleCommitBinding
import com.lxl.bt.net.NetApi
import com.lxl.bt.net.Result
import com.lxl.bt.retorfit.NetCallback
import com.lxl.bt.retorfit.RetrofitUtil
import com.lxl.bt.util.PickViewUtil
import com.lxl.bt.util.ToastUtil
import com.lxl.bt.view.TextWatcherAdapter
import com.yanzhenjie.sofia.Sofia

/**
 *Created by HouJie on 4/11/21
 */
class PayActivity : BaseActivity() {
    var pays = arrayOf("支付宝", "银联", "btc", "usdt")
    var payValues = arrayOf("1", "2", "3", "4")
    var icons = intArrayOf(R.mipmap.zhifubao, R.mipmap.yinlian, R.mipmap.btc, R.mipmap.ustd)
    val initPosition = intArrayOf(0)
    var dianliBean: DianliBean? = null
    var product: ProductBean? = null
    var payType = payValues[0]
    var count = 0f
    var payPrice = 0f
    val handler: Handler = Handler(Looper.getMainLooper())
    val api = RetrofitUtil.getInstance().create(NetApi::class.java, 0)
    private var mCheck = false
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding = DataBindingUtil.setContentView<ActivityPayBinding>(this, R.layout.activity_pay)
        val toolBarBind = DataBindingUtil.bind<ToolbarTitleCommitBinding>(binding.titleBar.root)
        dianliBean = intent.extras?.getSerializable("data") as DianliBean?
        product = intent.extras?.getSerializable("product") as ProductBean?
        //状态栏全透明全屏显示页面，布局能够延伸到状态栏和导航栏下方
        Sofia.with(this).invasionStatusBar()
                .statusBarLightFont() //                .statusBarDarkFont()
                .statusBarBackgroundAlpha(0)
                .invasionNavigationBar()
                .navigationBarBackgroundAlpha(0)
        initToolbar(toolBarBind)
        initPay(binding)
    }

    private fun initPay(binding: ActivityPayBinding) {


        val payBind = DataBindingUtil.bind<PopwindowBuyBinding>(binding.payLayout.root)
        payBind?.run {
            ivDel.visibility = View.GONE
            initPayEdt(this)
            llPayType.setOnClickListener {
                PickViewUtil.createPickView(it.context, { options1: Int, _: Int, _: Int, _: View? ->
                    payBind.ivPay.setImageResource(icons[options1])
                    initPosition[0] = options1
                    payType = payValues[options1]
                }, "支付方式", pays, initPosition[0])
            }

            product?.let {
                tvAllCount.text = it.coinName.toUpperCase()
                tvOrderPrice.text = it.defaultPrice
                tvTotalPrice.text = it.defaultPrice
                if ("1" == product?.type) {
                    tvLimit.text = "* 限额：最少购买1台"
                }

            }

            tvCommit.setOnClickListener {
                if (!mCheck) {
                    ToastUtil.showToast(it.context, "请先同意协议")
                    return@setOnClickListener
                }
                commit(binding)
            }
            val click: (View) -> Unit = {
                mCheck = !mCheck
                tvAgree.isSelected = mCheck
            }
            tvAgree.setOnClickListener(click)
            tvLeaseAgreement.setOnClickListener {
                WebviewActivity.intent(it.context,"Happy Kirin注册服务协议","http://oss.puxkj.com/default/1618389594284.html")
            }
        }
    }

    private fun PopwindowBuyBinding.commit(binding: ActivityPayBinding) {
        product?.let { product ->
            api.createOrder("", dianliBean?.dictDetailId ?: "",
                    edNum.text.toString(),
                    edAmount.text.toString(),
                    payType,
                    product.productId)
                    .enqueue(object : NetCallback<Result<CreateOrderBody>>() {
                        override fun onSuccess(result: Result<CreateOrderBody>?) {
                            result?.let {
                                handler.postDelayed({ onBackPressed() }, 500)
                                ToastUtil.showToast(binding.root.context, result.msg)
                            }
                        }

                        override fun onError(errorStr: String?) {
                            super.onError(errorStr)
                            ToastUtil.showToast(binding.root.context, errorStr)
                        }

                        override fun netLogin() {
                        }
                    })
        }
    }

    private fun initPayEdt(binding: PopwindowBuyBinding) {
        handlerAmountEdt(binding)
        handlerNumEdt(binding)
    }

    private fun handlerNumEdt(binding: PopwindowBuyBinding) {
        val numWatcher = object : TextWatcherAdapter() {
            override fun afterTextChanged(editable: Editable?) {
                val type = "1"
                if (binding.edNum.isFocused) {
                    getPrice(type, binding, editable, object : NetCallback<Result<String>>() {
                        override fun onSuccess(result: Result<String>?) {
                            binding.edAmount.text = Editable.Factory.getInstance()
                                    .newEditable(result?.data ?: "")
                        }

                        override fun netLogin() {
                        }
                    })
                }
            }
        }
        binding.edNum.addTextChangedListener(numWatcher)
    }

    private fun handlerAmountEdt(binding: PopwindowBuyBinding) {
        val amountWatcher = object : TextWatcherAdapter() {
            override fun afterTextChanged(editable: Editable?) {
                binding.tvTotalPrice.text = editable.toString()
                binding.tvOrderPrice.text = editable.toString()
                val type = "0"
                if (binding.edAmount.isFocused) {
                    getPrice(type, binding, editable, object : NetCallback<Result<String>>() {
                        override fun onSuccess(result: Result<String>?) {
                            binding.edNum.text = Editable.Factory.getInstance()
                                    .newEditable(result?.data ?: "")
                        }

                        override fun netLogin() {
                        }
                    })
                }
            }
        }
        binding.edAmount.addTextChangedListener(amountWatcher)
    }

    private fun getPrice(type: String, binding: PopwindowBuyBinding, s: Editable?, value: NetCallback<Result<String>>) {
        handler.removeCallbacksAndMessages(null)
        handler.postDelayed({
            api.getOrderPrice(type,
                    binding.edNum.text.toString(), s.toString(),
                    product?.productId ?: "")
                    .enqueue(value)
        }, 300)
    }

    private fun initToolbar(toolBarBind: ToolbarTitleCommitBinding?) {
        toolBarBind?.run {
            rlBack.visibility = View.VISIBLE
            rlBack.setOnClickListener { onBackPressed() }
            txtToolbarTitle.text = "支付"
        }
    }

    companion object {
        fun start(context: Context, item: DianliBean?, product: ProductBean?) {
            val starter = Intent(context, PayActivity::class.java)
            starter.putExtra("data", item)
            starter.putExtra("product", product)
            context.startActivity(starter)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }
}